package com.ruoyi.network.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.network.edge.EdgeContext;
import com.ruoyi.network.edge.EdgeHelper;
import com.ruoyi.network.edge.EdgeNetwork;
import com.ruoyi.network.websocket.EdgeWsClient;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class WebsocketMsgHandler90001 implements WebsocketMsgHandler {
	@Autowired
	private EdgeNetwork edgeNetwork;
	@Override
	public synchronized void invoke(EdgeWsClient edgeWsClient, JSONObject message) {
		String id = edgeWsClient.getId();
		JSONObject param = message.getJSONObject("param");
		JSONObject command = message.getJSONObject("command");
		String terminateId = param.getString("terminateId");
		String innerHost = param.getString("innerHost");
		Integer innerPort = param.getInteger("innerPort");
		Boolean isActive = param.getBoolean("isActive");
		log.info("终端id={} 收到命令 {}",id,message);
		//服务器端一个端口只与一个边缘端连接
		if (terminateId.equals(id)) {
			if(!StringUtils.isEmpty(innerHost) && innerPort != null) {
				//内网信息发生变化时,断开所有连接
				boolean isChangeProxy = isChangeProxy(innerHost,innerPort);
				if(isChangeProxy) {
					diableActive();
				}
				//设置内网连接信息
				edgeNetwork.setInnerHost(innerHost);
				edgeNetwork.setInnerPort(innerPort);
			}
			//根据指令激活/停用客户端
			if(!isActive) {
				diableActive();
			}else {
				edgeNetwork.setActive(isActive);
				log.info("激活边缘端");
			}
		}else {
			diableActive();
		}

	}

	/**
	 * @param innerHost
	 * @param innerPort 
	 */
	private boolean isChangeProxy(String innerHost, Integer innerPort) {
		if(!innerHost.equals(edgeNetwork.getInnerHost())) {
			return true;
		}
		if(edgeNetwork.getInnerPort() == null && innerPort != null) {
			return true;
		}
		if(edgeNetwork.getInnerPort().intValue() != innerPort.intValue()) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 */
	private void diableActive() {
		log.info("停用边缘端");
		edgeNetwork.setActive(false);
		EdgeHelper.closeClients(EdgeContext.all.keySet());
	}

}
